package cn.bonoon.handler.impl;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import cn.bonoon.core.plugins.LoginRecordService;
import cn.bonoon.handler.LoginSuccessHandler;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.util.RequestHelper;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * <pre>
 * 通过ajax的方式进行登录
 * </pre>
 * 
 * @author jackson
 * 
 */
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    protected final Log logger = LogFactory.getLog(this.getClass());
    
	@Autowired
	private LoginRecordService loginRecordSevice;

	@Autowired(required = false)
	private List<LoginSuccessHandler> handlers;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		LogonUser bu = (LogonUser) authentication.getPrincipal();
		try {
			loginRecordSevice.login(bu, RequestHelper.getAgent(request), RequestHelper.getIpAddress(request), true, request.getSession().getId());
		} catch (Throwable err) {
			// 忽略所有异常情况
			err.printStackTrace();
			logger.error("写登录记录异常", err);
		}

		try {
			if (null != handlers && !handlers.isEmpty()) {
				for (LoginSuccessHandler handler : handlers) {
					handler.onSuccess(request, response, authentication, bu);
				}
			}
		} catch (Throwable err) {
			err.printStackTrace();
			logger.error("子系统或插件定义的处理异常", err);
		}

		ObjectMapper objectMapper = new ObjectMapper();
		response.setHeader("Content-Type", "application/json;charset=UTF-8");
		JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
		try {
			// 成功为0
			objectMapper.writeValue(jsonGenerator, JsonResult.result());
		} catch (JsonProcessingException ex) {
			throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}
}
